package audit

import (
	"context"
	"sort"

	"gitee.com/liuxuezhan/ar-platform/rpc-client/agentClient/rpc"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/gameManageClient/client/game"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RebatesInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 代理返佣配置详情
func NewRebatesInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RebatesInfoLogic {
	return &RebatesInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RebatesInfoLogic) RebatesInfo(req *types.AgentRebateSettingInfoRequest) (resp *types.AgentRebateSettingInfo, err error) {
	_row, err := l.svcCtx.AgentRPC.AgentRebatesInfo(l.ctx, &rpc.AgentRebateSettingInfoRequest{
		UserId: req.UserId,
	})
	if err != nil {
		logc.Error(l.ctx, err)
		return nil, err
	}
	games, _err := l.svcCtx.GameManageRpc.GameCategoryList(l.ctx, &game.GameCategoryListReq{
		IsEnabled: 1,
		Pager: &game.Pager{
			Page: 1,
			Size: 10000,
		},
	})
	if _err != nil {
		logc.Error(l.ctx, err)
		return nil, err
	}
	_gameMap := make(map[string]struct {
		Id   int64
		Name string
		Code string
	})
	for _, _g := range games.List {
		_gameMap[_g.Code] = struct {
			Id   int64
			Name string
			Code string
		}{Id: _g.Id, Name: _g.Name, Code: _g.Code}
	}

	_gameRate := make([]types.GameRate, 0)
	_tmpGame := make(map[string]types.GameRate)
	for _, _g := range _row.GamesRate {
		rate := types.GameRate{
			GameId: _g.GameId,
			Game:   _g.Game,
			Rate:   _g.Rate,
			Code:   _g.Code,
		}
		// 存在游戏类型的,才显示,过滤掉已经排出的游戏
		if _, ok := _gameMap[_g.Code]; ok {
			_tmpGame[_g.Code] = rate
		}
		// _gameRate = append(_gameRate, rate)
	}
	for _code, _g := range _gameMap {
		if _tmp, ok := _tmpGame[_code]; !ok {
			_tmpGame[_code] = types.GameRate{
				GameId: _g.Id,
				Game:   _g.Name,
				Code:   _g.Code,
			}
		} else {
			_tmp.Game = _g.Name
			_tmpGame[_code] = _tmp
		}
	}
	for _, _gm := range _tmpGame {
		_gameRate = append(_gameRate, _gm)
	}
	sort.Slice(_gameRate, func(i, j int) bool {
		return _gameRate[i].GameId < _gameRate[j].GameId
	})
	resp = &types.AgentRebateSettingInfo{
		Id:           _row.Id,
		GamesRate:    _gameRate,
		LevelRate:    _row.LevelRate,
		LevelLimit:   _row.LevelLimit,
		ConditionNum: _row.ConditionNum,
		Remark:       _row.Remark,
		UserId:       _row.UserId,
	}
	return
}
